//
//  LSYReadPageViewController.m
//  LSYReader
//
//  Created by Labanotation on 16/5/30.
//  Copyright © 2016年 okwei. All rights reserved.
//

#import "LSYReadPageViewController.h"
#import "LSYReadViewController.h"
#import "LSYChapterModel.h"
#import "LSYMenuView.h"
#import "LSYCatalogViewController.h"
#import "UIImage+ImageEffects.h"
#import "LSYNoteModel.h"
#import "LSYMarkModel.h"
#import <objc/runtime.h>
#import "ReadFooterView.h"
#import "CZQCustomNavView.h"
#import "CZQMyMainSharView.h"
#import "ReadBookDirectoryVC.h"
#import "ReadBookSetView.h"
#import "OpenVipView.h"
#import "DownLoadView.h"
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "ReedBookFirstAdvViewController.h"

#define AnimationDelay 0.3

@interface LSYReadPageViewController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource,LSYMenuViewDelegate,UIGestureRecognizerDelegate,ReadBookDirectoryVCDelegate,LSYReadViewControllerDelegate>
{
    NSUInteger _chapter;    //当前显示的章节
    NSUInteger _page;       //当前显示的页数
    NSUInteger _chapterChange;  //将要变化的章节
    NSUInteger _pageChange;     //将要变化的页数
    BOOL _isTransition;     //是否开始翻页
}
@property (nonatomic,strong) UIPageViewController *pageViewController;
@property (nonatomic,getter=isShowBar) BOOL showBar; //是否显示状态栏
@property (nonatomic,strong) LSYMenuView *menuView; //菜单栏
@property (nonatomic,strong) LSYCatalogViewController *catalogVC;   //侧边栏
@property (nonatomic,strong) UIView * catalogView;  //侧边栏背景
@property (nonatomic,strong) LSYReadViewController *readView;   //当前阅读视图
@property (nonatomic,strong) CZQCustomNavView *topView;
@property (nonatomic,strong) ReadFooterView *bottomView;
@property (nonatomic,strong) UIImageView *advImageView;

@property (nonatomic,strong) ReadBookSetView *setView; //设置View

//获取屏幕亮度
@property (nonatomic,assign) CGFloat currentLight;

@end

@implementation LSYReadPageViewController

-(void)viewWillAppear:(BOOL)animated
{
    
    //获取屏幕亮度
    CGFloat currentLight = [[UIScreen mainScreen] brightness];
    
    self.currentLight = currentLight;
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
}

//试图完全显示更新小说
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.model = [LSYReadModel getLocalModelWithURL:self.resourceURL];
    
    [_pageViewController setViewControllers:@[[self readViewWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self updateReadModelWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
     [[UIScreen mainScreen] setBrightness: self.currentLight];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //禁止全屏返回
    self.fd_interactivePopDisabled = YES;
    
    
    [self addChildViewController:self.pageViewController];
    [_pageViewController setViewControllers:@[[self readViewWithChapter:_model.record.chapter page:_model.record.page]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    _chapter = _model.record.chapter;
    _page = _model.record.page;
    [self.view addGestureRecognizer:({
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
        tap.delegate = self;
        tap;
    })];
    [self.view addSubview:self.menuView];
    
    [self addChildViewController:self.catalogVC];
    [self.view addSubview:self.catalogView];
    [self.catalogView addSubview:self.catalogVC.view];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.bottomView];
    
    //底部广告
    _advImageView = [[UIImageView alloc]init];
    _advImageView.image = _page%2!=0?[UIImage imageNamed:@"底部广告2"]:[UIImage imageNamed:@"底部广告"];
    _advImageView.userInteractionEnabled = YES;
    [self.view addSubview:_advImageView];
    
    
    UILabel *advLable = [[UILabel alloc]init];
    advLable.text = @"广告";
    advLable.textAlignment = NSTextAlignmentCenter;
    advLable.backgroundColor = CSColorFromRGBA(0x000000, 0.5);
    advLable.layer.cornerRadius = 2;
    advLable.clipsToBounds = YES;
    advLable.textColor = CSWhiteColor;
    advLable.font = [UIFont systemFontOfSize:12];
    [self.advImageView addSubview:advLable];
    
    [_advImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.bottom.width.mas_equalTo(self.view);
        make.height.mas_equalTo((Iphone5?70:90));
        
    }];
    
    [advLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(35);
        make.height.mas_equalTo(16);
        make.top.mas_equalTo(self.advImageView).offset(5);
        make.right.mas_equalTo(self.advImageView).offset(-5);
        
    }];
    
    //添加笔记
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNotes:) name:LSYNoteNotification object:nil];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
}

-(void)addNotes:(NSNotification *)no
{
    LSYNoteModel *noteModel = no.object;
    LSYChapterModel *chapterModel = _model.record.chapterModel;
    noteModel.location += [chapterModel.pageArray[_model.record.page] integerValue];
    noteModel.chapter = _model.record.chapter;
    noteModel.recordModel = [_model.record copy];
    [[_model mutableArrayValueForKey:@"notes"] addObject:noteModel];    //这样写才能KVO数组变化
    [LSYReadUtilites showAlertTitle:nil content:@"保存笔记成功"];
}

-(BOOL)prefersStatusBarHidden
{
    return !_showBar;
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
#pragma mark  - event
-(void)tap:(UITapGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:self.view];
    if(point.x < kScreenW * 0.3 || point.x > kScreenW * 0.7 || point.y <kScreenH * 0.3 || point.y > kScreenH * 0.7)
        return;
    if(self.showBar)
    {
        //显示了则退回去
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.transform = CGAffineTransformIdentity;
            self.bottomView.transform = CGAffineTransformIdentity;
        }completion:^(BOOL finished) {
            self.topView.hidden = YES;
            self.bottomView.hidden = YES;
        }];
    }else
    {
        //没显示则显示出来
        self.topView.hidden = NO;
        self.bottomView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.transform = CGAffineTransformMakeTranslation(0, toolH);
            self.bottomView.transform = CGAffineTransformMakeTranslation(0,-(adaptTabBar));
        }];
    }
    self.showBar = !self.showBar;
    //更新状态栏是不是显示
    [[UIApplication sharedApplication] setStatusBarHidden:!self.showBar];
}

#pragma mark  - setter or getter
-(void)setShowBar:(BOOL)showBar
{
    _showBar = showBar;
    self.pageViewController.view.userInteractionEnabled = !showBar;
}


#pragma mark - init
-(CZQCustomNavView *)topView
{
    if(_topView == nil)
    {
        _topView = [[CZQCustomNavView alloc]initWithFrame:CGRectMake(0, -(toolH), kScreenW,toolH)];
        _topView.hidden = YES;
        _topView.bgView.hidden = YES;
        _topView.backgroundColor = CSColorFromRGB(0x333333);
        [_topView.rightBtn setImage:@"分享"];
        [_topView.rightBtn addTarget:self action:@selector(share)];
        _topView.rightBtn.hidden = NO;
    }
    return _topView;
}
-(ReadFooterView *)bottomView
{
    if(_bottomView == nil)
    {
        _bottomView = [[ReadFooterView alloc]initWithFrame:CGRectMake(0, kScreenH - (Iphone5?70:90), kScreenW, adaptTabBar)];
        _bottomView.hidden = YES;
        [_bottomView.listBtn addTarget:self action:@selector(directory)];
        [_bottomView.setBtn addTarget:self action:@selector(set)];
        [_bottomView.nightBtn addTarget:self action:@selector(changeBg:)];
        [_bottomView.loadDownBtn addTarget:self action:@selector(loadDown)];
        
        //将广告置为顶部图层
        [self.view bringSubviewToFront:self.readView.adviImageView];
    }
    return _bottomView;
    
}




-(UIPageViewController *)pageViewController
{
    if (!_pageViewController) {
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        _pageViewController.doubleSided = NO;
        [self.view addSubview:_pageViewController.view];
    }
    return _pageViewController;
}


#pragma mark - ReadBookDirectoryVC Delegate

/**
 目录点击回调
 */
-(void)catalog:(ReadBookDirectoryVC *)catalog didSelectChapter:(NSUInteger)chapter page:(NSUInteger)page
{
     [_pageViewController setViewControllers:@[[self readViewWithChapter:chapter page:page]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
    [self updateReadModelWithChapter:chapter page:page];
    [self hiddenCatalog];
    
}


#pragma mark - ReadBookSetViewDelegate
//字体设置
-(void)ReadBookSetViewFontSize:(ReadBookSetView *)bottomView
{
    
}

#pragma mark -  UIGestureRecognizer Delegate
//解决TabView与Tap手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

-(LSYMenuView *)menuView
{
    if (!_menuView) {
        _menuView = [[LSYMenuView alloc] init];
        _menuView.hidden = YES;
        _menuView.delegate = self;
        _menuView.recordModel = _model.record;
    }
    return _menuView;
}



#pragma mark - Create Read View Controller

-(LSYReadViewController *)readViewWithChapter:(NSUInteger)chapter page:(NSUInteger)page{

    
    if (_model.record.chapter != chapter) {
        [self updateReadModelWithChapter:chapter page:page];
        [_model.record.chapterModel updateFont];
    }
    _readView = [[LSYReadViewController alloc] init];
    _readView.recordModel = _model.record;
    _readView.content = [_model.chapters[chapter] stringOfPage:page];
    _readView.delegate = self;
    NSLog(@"_readGreate");
    
    return _readView;
}
-(void)updateReadModelWithChapter:(NSUInteger)chapter page:(NSUInteger)page
{
    _chapter = chapter;
    _page = page;
    _model.record.chapterModel = _model.chapters[chapter];
    _model.record.chapter = chapter;
    _model.record.page = page;
    _model.font = [NSNumber numberWithFloat:[LSYReadConfig shareInstance].fontSize];
    [LSYReadModel updateLocalModel:_model url:_resourceURL];
}

#pragma mark - Read View Controller Delegate
-(void)readViewEndEdit:(LSYReadViewController *)readView
{
    for (UIGestureRecognizer *ges in self.pageViewController.view.gestureRecognizers) {
        if ([ges isKindOfClass:[UIPanGestureRecognizer class]]) {
            ges.enabled = YES;
            break;
        }
    }
}
-(void)readViewEditeding:(LSYReadViewController *)readView
{
    for (UIGestureRecognizer *ges in self.pageViewController.view.gestureRecognizers) {
        if ([ges isKindOfClass:[UIPanGestureRecognizer class]]) {
            ges.enabled = NO;
            break;
        }
    }
}
#pragma mark -PageViewController DataSource
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{

    _pageChange = _page;
    _chapterChange = _chapter;

    if (_chapterChange==0 &&_pageChange == 0) {
        return nil;
    }
    if (_pageChange==0) {
        _chapterChange--;
        _pageChange = _model.chapters[_chapterChange].pageCount-1;
    }
    else{
        _pageChange--;
    }
    
    return [self readViewWithChapter:_chapterChange page:_pageChange];
    
}
- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{

    _pageChange = _page;
    _chapterChange = _chapter;
    if (_pageChange == _model.chapters.lastObject.pageCount-1 && _chapterChange == _model.chapters.count-1) {
        return nil;
    }
    if (_pageChange == _model.chapters[_chapterChange].pageCount-1) {
        _chapterChange++;
        _pageChange = 0;
        NSLog(@"%ld",_page);
        
//        新的章节提示广告
        [self newChapterTip];
    }
    else{
        _pageChange++;
    }
    return [self readViewWithChapter:_chapterChange page:_pageChange];
}
#pragma mark -PageViewController Delegate
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    
    
    if (!completed) {
        LSYReadViewController *readView = previousViewControllers.firstObject;
        _readView = readView;
        _page = readView.recordModel.page;
        _chapter = readView.recordModel.chapter;
       
        
        
        
    }
    else{
        
        
        [self updateReadModelWithChapter:_chapter page:_page];
    }
    
    _advImageView.hidden = NO;
    
    _advImageView.image = _page%2!=0?[UIImage imageNamed:@"底部广告2"]:[UIImage imageNamed:@"底部广告"];
}
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers
{
    _chapter = _chapterChange;
    _page = _pageChange;
    
    _advImageView.image = _page%2!=0?[UIImage imageNamed:@"底部广告2"]:[UIImage imageNamed:@"底部广告"];
    _advImageView.hidden = YES;
    
    
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    
    if (@available(iOS 11.0, *)){
        _pageViewController.view.frame = self.view.frame;
        _menuView.frame = self.view.frame;
        _catalogVC.view.frame = CGRectMake(0, 0, ViewSize(self.view).width-100, ViewSize(self.view).height);
    } else {
        _pageViewController.view.frame = self.view.frame;
        _menuView.frame = self.view.frame;
        _catalogView.frame = CGRectMake(-ViewSize(self.view).width, 0, 2*ViewSize(self.view).width, ViewSize(self.view).height);
        _catalogVC.view.frame = CGRectMake(0, 0, ViewSize(self.view).width-100, ViewSize(self.view).height);
    }
    
    [_catalogVC reload];
}

#pragma mark - 目录
-(void)directory
{
    ReadBookDirectoryVC *dirVC = [[ReadBookDirectoryVC alloc]init];
    dirVC.readModel = _model;
    dirVC.catalogDelegate = self;
    [self.navigationController pushViewController:dirVC animated:YES];
}

#pragma mark - 设置
-(void)set
{
    ReadBookSetView *setView = [[ReadBookSetView alloc]init];
    [setView showWithAnimation];
    self.setView = setView;
    
    //行间距
    [setView.distancSlider addTarget:self action:@selector(distanse:) forControlEvents:UIControlEventValueChanged];
    
    //改变字体
    [setView.minFontBtn addTarget:self action:@selector(fontChange:) forControlEvents:UIControlEventTouchUpInside];
    [setView.moreFontBtn addTarget:self action:@selector(fontChange:) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - 改变行距
-(void)distanse:(UISlider *)sender
{
    [LSYReadConfig shareInstance].lineSpace = sender.value;
    
    [_pageViewController setViewControllers:@[[self readViewWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self updateReadModelWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page];
}

#pragma mark - 改变字体大小

-(void)fontChange:(UIButton *)sender
{
    
    if (sender == self.setView.moreFontBtn) {
        
        if (floor([LSYReadConfig shareInstance].fontSize) == floor(MaxFontSize)) {
            [MBProgressHUD showText:@"超过最大设置字体"];
            return;
        }
        [LSYReadConfig shareInstance].fontSize++;
    }
    else{
        if (floor([LSYReadConfig shareInstance].fontSize) == floor(MinFontSize)){
            [MBProgressHUD showText:@"超过最小设置字体"];
            return;
        }
        [LSYReadConfig shareInstance].fontSize--;
    }
    
    [_model.record.chapterModel updateFont];
    
    for (int i = 0; i < _model.chapters.count; i++) {
        [_model.chapters[i] updateFont];
    }
    
    [_pageViewController setViewControllers:@[[self readViewWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self updateReadModelWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page];
}


#pragma mark - 白天黑夜切换
-(void)changeBg:(UIButton *)sender
{
    
    sender.selected = !sender.selected;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LSYThemeNotification object:sender.selected?CSColorFromRGB(0x1C1C1C):CSWhiteColor];
    
    [LSYReadConfig shareInstance].fontColor = sender.selected?CSColorFromRGB(0x757575):CSColorFromRGB(0x010100);
    
    [_pageViewController setViewControllers:@[[self readViewWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self updateReadModelWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page];
    
}


#pragma mark - 下载
-(void)loadDown
{
    OpenVipView *vipView = [[OpenVipView alloc]init];
    [vipView showWithAnimation];
    
    DownLoadView *loadView = [[DownLoadView alloc]init];
//    [loadView addViews];
}

#pragma mark - 新的章节提示广告
-(void)newChapterTip
{
    //新的章节提示
    ReedBookFirstAdvViewController *advVC = [[ReedBookFirstAdvViewController alloc]init];
    advVC.readModel = self.model;
    [self.navigationController pushViewController:advVC animated:NO];
}

#pragma mark - 分享
-(void)share
{
    WS(weakSelf);
    
    CZQMyMainSharView *shareView = [[CZQMyMainSharView alloc]init];
    [shareView onlyShare];
    [shareView showWithAnimation];
    
    shareView.shareClick = ^(NSInteger index) {
        
        [weakSelf shareBtnClick:index];
        
    };
}

#pragma mark - 分享回调
-(void)shareBtnClick:(NSInteger)index
{
    
    if (index == 0) {
        //微信朋友圈
        
        [self shareToPlatform:UMSocialPlatformType_WechatTimeLine];
        
    }else if (index == 1){
        
        //微信好友
        [self shareToPlatform:UMSocialPlatformType_WechatSession];
        
    }
    else if (index == 2){
        
        //5,//qq空间
        [self shareToPlatform:UMSocialPlatformType_Qzone];
        
    }
    else if (index == 3){
        
        //4,//QQ聊天页面
        [self shareToPlatform:UMSocialPlatformType_QQ];
        
    }
    
}

- (void)shareToPlatform:(UMSocialPlatformType)platformType{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"万能追书" descr:@"" thumImage:PlaceHold];
    
    //设置网页地址
    shareObject.webpageUrl = @"htps://www.baidu.com";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    /**
     设置分享
     
     @param data 分享返回信息
     @param error 失败信息
     @param UMSocialPlatformType 分享平台
     */
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            //错误码
            
            NSString *result;
            switch (error.code) {
                case UMSocialPlatformErrorType_Unknow:
                    result = @"未知错误";
                    break;
                case UMSocialPlatformErrorType_NotSupport:
                    result = @"不支持（url scheme 没配置，或者没有配置-ObjC， 或则SDK版本不支持或则客户端版本不支持";
                    break;
                case UMSocialPlatformErrorType_AuthorizeFailed:
                    result = @"授权失败";
                    break;
                case UMSocialPlatformErrorType_ShareFailed:
                    result = @"分享失败";
                    break;
                case UMSocialPlatformErrorType_RequestForUserProfileFailed:
                    result = @"请求用户信息失败";
                    break;
                case UMSocialPlatformErrorType_ShareDataNil:
                    result = @"分享内容为空";
                    break;
                case UMSocialPlatformErrorType_ShareDataTypeIllegal:
                    result = @"分享内容不支持";
                    break;
                case UMSocialPlatformErrorType_CheckUrlSchemaFail:
                    result = @"schemaurl fail";
                    break;
                case UMSocialPlatformErrorType_NotInstall:
                    result = @"应用未安装";
                    break;
                case UMSocialPlatformErrorType_Cancel:
                    result = @"您已取消分享";
                    break;
                case UMSocialPlatformErrorType_NotNetWork:
                    result = @"网络异常";
                    break;
                case UMSocialPlatformErrorType_SourceError:
                    result = @"第三方错误";
                    break;
                case UMSocialPlatformErrorType_ProtocolNotOverride:
                    result = @"对应的    UMSocialPlatformProvider的方法没有实现";
                    break;
                default:
                    break;
            }
            
            [MBProgressHUD showText:result];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}


#warning 暂未用到

-(LSYCatalogViewController *)catalogVC
{
    if (!_catalogVC) {
        _catalogVC = [[LSYCatalogViewController alloc] init];
        _catalogVC.readModel = _model;
//        _catalogVC.catalogDelegate = self;
    }
    return _catalogVC;
}
-(UIView *)catalogView
{
    if (!_catalogView) {
        _catalogView = [[UIView alloc] init];
        _catalogView.backgroundColor = [UIColor clearColor];
        _catalogView.hidden = YES;
        [_catalogView addGestureRecognizer:({
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenCatalog)];
            tap.delegate = self;
            tap;
        })];
    }
    return _catalogView;
}

#pragma mark - Privite Method
-(void)catalogShowState:(BOOL)show
{
    show?({
        _catalogView.hidden = !show;
        [UIView animateWithDuration:AnimationDelay animations:^{
            _catalogView.frame = CGRectMake(0, 0,2*ViewSize(self.view).width, ViewSize(self.view).height);
            
        } completion:^(BOOL finished) {
            [_catalogView insertSubview:[[UIImageView alloc] initWithImage:[self blurredSnapshot]] atIndex:0];
        }];
    }):({
        if ([_catalogView.subviews.firstObject isKindOfClass:[UIImageView class]]) {
            [_catalogView.subviews.firstObject removeFromSuperview];
        }
        [UIView animateWithDuration:AnimationDelay animations:^{
            _catalogView.frame = CGRectMake(-ViewSize(self.view).width, 0, 2*ViewSize(self.view).width, ViewSize(self.view).height);
        } completion:^(BOOL finished) {
            _catalogView.hidden = !show;
            
        }];
    });
}
-(void)hiddenCatalog
{
    [self catalogShowState:NO];
}
- (UIImage *)blurredSnapshot {
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)), NO, 1.0f);
    [self.view drawViewHierarchyInRect:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)) afterScreenUpdates:NO];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIImage *blurredSnapshotImage = [snapshotImage applyLightEffect];
    UIGraphicsEndImageContext();
    return blurredSnapshotImage;
}
#pragma mark - Menu View Delegate
-(void)menuViewDidHidden:(LSYMenuView *)menu
{
    _showBar = NO;
    [self setNeedsStatusBarAppearanceUpdate];
}
-(void)menuViewDidAppear:(LSYMenuView *)menu
{
    _showBar = YES;
    [self setNeedsStatusBarAppearanceUpdate];
    
}
-(void)menuViewInvokeCatalog:(LSYBottomMenuView *)bottomMenu
{
    [_menuView hiddenAnimation:NO];
    [self catalogShowState:YES];
    
}

-(void)menuViewJumpChapter:(NSUInteger)chapter page:(NSUInteger)page
{
    [_pageViewController setViewControllers:@[[self readViewWithChapter:chapter page:page]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self updateReadModelWithChapter:chapter page:page];
}

//改变字体大小
-(void)menuViewFontSize:(LSYBottomMenuView *)bottomMenu
{
    
    [_model.record.chapterModel updateFont];
    
    for (int i = 0; i < _model.chapters.count; i++) {
        [_model.chapters[i] updateFont];
    }
    
    [_pageViewController setViewControllers:@[[self readViewWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self updateReadModelWithChapter:_model.record.chapter page:(_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page];
}

-(void)menuViewMark:(LSYTopMenuView *)topMenu
{
    
    BOOL isMarked = FALSE;
    
    LSYRecordModel *recordModel = _model.record;
    LSYChapterModel *chapterModel = recordModel.chapterModel;
    
    NSUInteger startIndex = [chapterModel.pageArray[recordModel.page] integerValue];
    
    NSUInteger endIndex = NSUIntegerMax;
    
    if (recordModel.page < chapterModel.pageCount - 1) {
        endIndex = [chapterModel.pageArray[recordModel.page + 1] integerValue];
    }
    
    NSMutableArray *markedArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < _model.marks.count; i++) {
        LSYMarkModel *markModel = _model.marks[i];
        if (markModel.location >= startIndex && markModel.location <= endIndex) {
            isMarked = YES;
            [markedArray addObject:markModel];
        }
    }
    
    if (isMarked) {
        [[_model mutableArrayValueForKey:@"marks"] removeObjectsInArray:markedArray];
    } else {
        LSYRecordModel *recordModel = _model.record;
        LSYMarkModel *markModel = [[LSYMarkModel alloc] init];
        markModel.date = [NSDate date];
        markModel.location = [recordModel.chapterModel.pageArray[recordModel.page] integerValue];
        markModel.length = 0;
        markModel.chapter = recordModel.chapter;
        markModel.recordModel = [_model.record copy];
        [[_model mutableArrayValueForKey:@"marks"] addObject:markModel];
        //[_model.marksRecord setObject:markModel forKey:key];
    }
    
    _menuView.topView.state = !isMarked;
}
@end
